package org.budo.xml;

import java.util.HashMap;
import java.util.Map;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * 对应一个Xml节点
 * 
 * @author lmw
 */
@Getter
@Setter
@NoArgsConstructor
public class DomXmlObject extends AbstractXmlObject {
    private Node node;

    public DomXmlObject(Node node) {
        this.node = node;
    }

    @Override
    public String getNodeName() {
        if (null == this.node) {
            return null;
        }

        return this.node.getNodeName();
    }

    @Override
    public String getTextContent() {
        if (null == this.node) {
            return null;
        }

        return this.node.getTextContent();
    }

    @Override
    public XmlObject[] getChildNodeArray() {
        if (null == this.node) {
            return null;
        }

        NodeList childNodes = this.node.getChildNodes();
        int len = childNodes.getLength();

        XmlObject[] xmlObjects = new XmlObject[len];
        for (int i = 0; i < len; i++) {
            Node child = childNodes.item(i);
            xmlObjects[i] = new DomXmlObject(child);
        }

        return xmlObjects;
    }

    @Override
    public Map<String, String> getAttributeMap() {
        if (null == this.node) {
            return null;
        }

        NamedNodeMap attributes = this.node.getAttributes();
        if (null == attributes) {
            return null;
        }

        Map<String, String> attributeMap = new HashMap<String, String>();
        int len = attributes.getLength();
        for (int i = 0; i < len; i++) {
            Node attribute = attributes.item(i);
            String nodeName = attribute.getNodeName();
            String nodeValue = attribute.getNodeValue();

            attributeMap.put(nodeName, nodeValue);
        }

        return attributeMap;
    }

    @Override
    public XmlObject removeChildNodeByName(String nodeName) {
        if (null == this.node) {
            return null;
        }

        XmlObject[] childNodeArray = this.getChildNodeArrayByName(nodeName);
        for (XmlObject xmlObject : childNodeArray) {
            Node childNode = ((DomXmlObject) xmlObject).node;
            this.node.removeChild(childNode);
        }

        return this;
    }
}